package top.tangyh.lamp.care.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.pagehelper.util.StringUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.tangyh.lamp.care.mapper.BHl7RkDetailMapper;
import top.tangyh.lamp.care.service.BHl7RkDetailService;
import top.tangyh.basic.base.service.impl.SuperServiceImpl;
import top.tangyh.lamp.care.manager.BHl7RkDetailManager;
import top.tangyh.lamp.care.entity.BHl7RkDetail;
import top.tangyh.lamp.care.vo.query.PatientHistoryPageQueryVO;
import top.tangyh.lamp.care.vo.result.Hl7RkDetailOutVO;
import top.tangyh.lamp.care.vo.result.PageOutputDTO;
import top.tangyh.lamp.care.vo.save.BHl7RkDetailSaveVO;
import top.tangyh.lamp.care.vo.update.BHl7RkDetailUpdateVO;
import top.tangyh.lamp.care.vo.result.BHl7RkDetailResultVO;
import top.tangyh.lamp.care.vo.query.BHl7RkDetailPageQuery;
import top.tangyh.lamp.common.properties.SystemProperties;
import top.tangyh.lamp.common.utils.ConvertUtil;
import top.tangyh.lamp.common.utils.PDateUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 业务实现类
 * 入科明细表
 * </p>
 *
 * @author zqb
 * @date 2024-07-15 11:16:18
 * @create [2024-07-15 11:16:18] [zqb] [代码生成器生成]
 */
@Slf4j
@RequiredArgsConstructor
@Service
@Transactional(readOnly = true)
public class BHl7RkDetailServiceImpl extends SuperServiceImpl<BHl7RkDetailManager, Long, BHl7RkDetail> implements BHl7RkDetailService {

    @Autowired
    protected SystemProperties systemProperties;

    private final BHl7RkDetailMapper bHl7RkDetailMapper;

    @Override
    public PageOutputDTO<Hl7RkDetailOutVO> selectHistoryPatientsPage(PatientHistoryPageQueryVO patientHistoryPageQueryVO) {
//        LambdaQueryWrapper<BHl7RkDetail> wrapperQuery = new LambdaQueryWrapper<>();
//        if (null != patientHistoryPageQueryVO.getStartTime() && null != patientHistoryPageQueryVO.getEndTime()) {
//            String startTimeStr = DateUtil.formatDateTime(new Date(patientHistoryPageQueryVO.getStartTime()));
//            String endTimeStr = DateUtil.formatDateTime(new Date(patientHistoryPageQueryVO.getEndTime()));
//
//            wrapperQuery.apply("rk_time between '" + startTimeStr + "' and '" + endTimeStr + "'");
//        }
//        if (null != patientHistoryPageQueryVO.getStartTime() && null == patientHistoryPageQueryVO.getEndTime()) {
//            String startTimeStr = DateUtil.formatDateTime(new Date(patientHistoryPageQueryVO.getStartTime()));
//            wrapperQuery.apply("rk_time >='" + startTimeStr + "' ");
//        }
//        wrapperQuery.and(StringUtil.isNotEmpty(patientHistoryPageQueryVO.getNameOrHospitalNum()), wq -> wq
//                        .eq(StringUtil.isNotEmpty(patientHistoryPageQueryVO.getNameOrHospitalNum()), BHl7RkDetail::getPatientName, patientHistoryPageQueryVO.getNameOrHospitalNum())
//                        .or()
//                        .eq(StringUtil.isNotEmpty(patientHistoryPageQueryVO.getNameOrHospitalNum()), BHl7RkDetail::getHospitalNumber, patientHistoryPageQueryVO.getNameOrHospitalNum()))
//                .orderByDesc(BHl7RkDetail::getRkTime);
//
//        List<BHl7RkDetail> list = this.list(wrapperQuery);
//
//
//        Map<String, List<BHl7RkDetail>> collects = list.stream().collect(Collectors.groupingBy(BHl7RkDetail::getHospitalNumber));
        LocalDateTime startTime = Optional.ofNullable(patientHistoryPageQueryVO.getStartTime())
                .map(PDateUtils::getDateTimeOfTimestamp)
                .orElse(null);

        LocalDateTime endTime = Optional.ofNullable(patientHistoryPageQueryVO.getEndTime())
                .map(PDateUtils::getDateTimeOfTimestamp)
                .orElse(null);
        List<BHl7RkDetail> list=bHl7RkDetailMapper.selectHistoryPatients(startTime,endTime,patientHistoryPageQueryVO.getNameOrHospitalNum());
//        String icuCode = systemProperties.getIcuCode();
//        //至少进过icu
//        Iterator<Map.Entry<String, List<BHl7RkDetail>>> it = collects.entrySet().iterator();
//        while (it.hasNext()) {
//            Map.Entry<String, List<BHl7RkDetail>> entry = it.next();
//            List<BHl7RkDetail> poList = entry.getValue();
//            try {
//                if (CollectionUtils.isNotEmpty(poList)) {
//                    Boolean haveIcuDept = poList.stream().filter(m -> m.getDeptIdent() != null && m.getDeptIdent().equals(icuCode)).findAny().isPresent();
//                    //如果该病人没经过icu 则过滤掉
//                    if (!haveIcuDept) {
//                        it.remove();
//                    }
//                } else {
//                    it.remove();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//                System.out.println(e.getMessage());
//            }
//
//
//        }


//        List<BHl7RkDetail> listResult = new ArrayList<>();
//        for (Map.Entry<String, List<BHl7RkDetail>> entry : collects.entrySet()) {
//            List<BHl7RkDetail> poList = entry.getValue();
//            if (!CollectionUtils.isEmpty(poList)) {
//                // listResult.add(poList.get(0));
//                //取日期最早的那条数据
//                Comparator<BHl7RkDetail> comparator = Comparator.comparing(BHl7RkDetail::getRkTime);
//                BHl7RkDetail minObject = poList.stream().min(comparator).get();
//                listResult.add(minObject);
//            }
//        }

        // listResult.stream().sorted(Comparator.comparing(YxHl7RkDetailPO::getRkTime).reversed()).collect(Collectors.toList());
//        Collections.sort(listResult, new CalendarComparator());

        int current = patientHistoryPageQueryVO.getPage();
        int size = patientHistoryPageQueryVO.getSize();

        Page<BHl7RkDetail> page = new Page<>(current, size);
        int count = list.size();
        List<BHl7RkDetail> pageList = new ArrayList<>();
        //计算当前页第一条数据的下标
        int currId = current > 1 ? (current - 1) * size : 0;
        for (int i = 0; i < size && i < count - currId; i++) {
            pageList.add(list.get(currId + i));
        }
        page.setSize(size);
        page.setCurrent(current);
        page.setTotal(count);
        //计算分页总页数
        page.setPages(count % 10 == 0 ? count / 10 : count / 10 + 1);
        page.setRecords(pageList);

        return new PageOutputDTO<>(page.getTotal(), page.getPages(), page.getCurrent(),
                ConvertUtil.convertList(page.getRecords(), Hl7RkDetailOutVO.class));
    }

    // 时间倒序排序
    private static class CalendarComparator implements Comparator {
        @Override
        public int compare(Object object1, Object object2) {// 实现接口中的方法
            BHl7RkDetail p1 = (BHl7RkDetail) object1; // 强制转换
            BHl7RkDetail p2 = (BHl7RkDetail) object2;
            return p2.getRkTime().compareTo(p1.getRkTime());
        }
    }


    @Override
    public List<Hl7RkDetailOutVO> selectRkListOfHistoryPatientNew(String patientIdent, String hospitalNumber) {
        return bHl7RkDetailMapper.selectRkListOfHistoryPatientNew(patientIdent,hospitalNumber);
    }

    @Override
    public BHl7RkDetail selectLastRk(String hospitalNumber) {
        // 创建LambdaQueryWrapper对象

        return bHl7RkDetailMapper.selectOneByHospitalNumber(hospitalNumber);

    }


    @Override
    public BHl7RkDetail selectRkByPatientIdentAndRkTime(String patientIdent, LocalDateTime rkTime, Long id) {
        List<BHl7RkDetail> result = bHl7RkDetailMapper.selectNextRkByPatientIdentAndRkTime(patientIdent, rkTime,id);
        if(CollectionUtil.isNotEmpty(result)){
            return result.get(0);
        }
        else{
            return null;
        }

    }

}


